package com.cyy.learn.fileRename

import cn.hutool.core.io.FileUtil
import cn.hutool.core.util.XmlUtil
import cn.hutool.json.JSONUtil
import cn.hutool.json.XML
//import cn.hutool.core.util.XmlUtil
import com.cyy.util.FileChooserUtil
import com.cyy.util.TooltipUtil
import javafx.beans.property.SimpleIntegerProperty
import javafx.beans.property.SimpleStringProperty
import javafx.collections.FXCollections
import javafx.geometry.Orientation
import javafx.geometry.Pos
import javafx.scene.control.Menu
import javafx.scene.control.Spinner
import javafx.scene.control.TableView
import org.apache.commons.io.FileUtils
//import org.apache.commons.io.FileUtils
import tornadofx.*
import java.io.File

lateinit var ruleTableView: TableView<Rule>
lateinit var fileInfoTableView: TableView<FileRename>
val filePrefixAddableText = SimpleStringProperty("")
val filePostfixAddableText = SimpleStringProperty("")
val filePrefix = SimpleStringProperty("")
val filePostfix = SimpleStringProperty("")

val fileQueryString = SimpleStringProperty("")
val fileReplaceString = SimpleStringProperty("")

val startNumberOfRenameTab = SimpleIntegerProperty(0)

class FileRenameV : View("重命名") {
    val data: FileRenameController by inject()


    override val root = borderpane {
        top = hbox(10) {
            button("添加文件") {
                action {
                    data.addFileAction()
                }
            }
            button("添加文件夹") {
                action {
                    data.addFolderAction()
                }
            }
            button("预览") {
                action {
                    data.previewAction()
                }
            }
            button("重命名") {
                action {
                    data.renameAction()
                }
            }
            alignment = Pos.CENTER
        }

        center = splitpane(orientation = Orientation.VERTICAL) {

            vbox(5) {
                hbox(5) {
                    label("格式化：")
                    textfield(filePrefix) {
                        promptText = "文件前缀"
                        setOnKeyReleased {
                            data.generateRenameDestFilesOfFormat()
                        }
                    }
                    textfield(filePostfix) {
                        promptText = "文件后缀"
                        setOnKeyReleased {
                            data.generateRenameDestFilesOfFormat()
                        }
                    }
                    label("开始数字：${startNumberOfRenameTab.value}")
                    textfield(startNumberOfRenameTab) {
                    }
//                    spinner(startNumberOfRenameTab.value, Integer.MAX_VALUE, 0){
//                        valueProperty().integerBinding(startNumberOfRenameTab){
//                            startNumberOfRenameTab.value=value
//                            value
//                        }
//                    }

                }

                hbox(5) {
                    label("替换文本：")
                    textfield(fileQueryString) {
                        promptText = "查找"
                        setOnKeyReleased {
                            data.generateRenameDestFilesOfReplace()
                        }
                    }
                    textfield(fileReplaceString) {
                        promptText = "替换成"
                        setOnKeyReleased {
                            data.generateRenameDestFilesOfReplace()
                        }
                    }
                }

                hbox(5) {
                    label("添加文本：")
                    textfield(filePrefixAddableText) {
                        promptText = "文件名称之前内容"
                        setOnKeyReleased {
                            data.generateRenameDestFilesOfAddable()
                        }
                    }
                    textfield(filePostfixAddableText) {
                        promptText = "文件名称之后内容"
                        setOnKeyReleased {
                            data.generateRenameDestFilesOfAddable()
                        }
                    }
                }
            }

            vbox(5) {
                hbox(5) {
                    button("添加") {
                        action {
                            data.addRoleTableAction()
                        }
                    }
                    button("移除") {
                        action {
                            data.removeRuleTableAction()
                        }
                    }
                    button("上移") {
                        action {
                            data.upRuleTableAction()
                        }
                    }
                    button("下移") {
                        action {
                            data.downRuleTableAction()
                        }
                    }
                }

                ruleTableView = tableview(data.rules) {
                    column("序列", Rule::order)
                    column("规则", Rule::rule)
                    column("说明", Rule::explain)
                }
            }

            vbox(5) {
                fileInfoTableView = tableview(data.files) {
                    column("状态", FileRename::status).prefWidth(75)
                    column("名称", FileRename::fileName).prefWidth(75)
                    column("新名称", FileRename::newFileName).prefWidth(75)
                    column("错误信息", FileRename::errorInfo).prefWidth(75)
                    column("路径", FileRename::filesPath).prefWidth(75)

                    contextmenu {
                        item("Delete") {
                            action {
                                if (selectedItem != null) {
                                    data.removeFile()
                                }
                            }
                        }
                    }
                }
            }
        }
        paddingAll = 10.0
    }
}

class FileRename1(filePrefixTextField: String, filePostfixTextField: String) {
    val filePrefixTextFieldProperty = stringProperty(filePrefixTextField)
    var filePrefixTextField by filePrefixTextFieldProperty

    val filePostfixTextFieldProperty = stringProperty(filePostfixTextField)
    var filePostfixTextField by filePostfixTextFieldProperty
}

class Rule(order: String, rule: String, explain: String) {
    val orderProperty = stringProperty(order)
    var order by orderProperty

    val ruleProperty = stringProperty(rule)
    var rule by ruleProperty

    val explainProperty = stringProperty(explain)
    var explain by explainProperty
}

class FileRename(status: String, fileName: String, newFileName: String, errorInfo: String, filesPath: String) {
    val statusProperty = stringProperty(status)
    var status by statusProperty

    val fileNameProperty = stringProperty(fileName)
    var fileName by fileNameProperty

    val errorInfoProperty = stringProperty(errorInfo)
    var errorInfo by errorInfoProperty

    val filesPathProperty = stringProperty(filesPath)
    var filesPath by filesPathProperty

    val newFileNameProperty = stringProperty(newFileName)
    var newFileName by newFileNameProperty
}

//class FileRenameModel : ItemViewModel<fileRename>() {
//    val status
//
//}
class FileRenameController : Controller() {

    val files = FXCollections.observableArrayList<FileRename>()
    val rules = FXCollections.observableArrayList<Rule>()

    fun addFileAction() {
        val file = FileChooserUtil.chooseFile()
        if (file != null) {
            files.add(FileRename("true", file!!.getName(), "", "", file!!.getPath()))
        }
    }

    fun addFolderAction() {
        val folderFile = FileChooserUtil.chooseDirectory()
        if (folderFile != null) {
            for (file in FileUtils.listFiles(folderFile, null, false)) {
                files.add(FileRename("true", file.getName(), "", "", file.getPath()))
            }
        }
    }

    fun previewAction() {}

    fun renameAction() {
        for (fileInfoTableDatum in files) {
            if ("true" == fileInfoTableDatum.status) {
                val file = File(fileInfoTableDatum.filesPath)
                val newFile = File(file.parent, fileInfoTableDatum.newFileName)
                file.renameTo(newFile)
                fileInfoTableDatum.fileName = newFile.name
                fileInfoTableDatum.filesPath = newFile.path
            }
        }
//        fileInfoTableView.refresh()
        TooltipUtil.showToast("重命名成功！")
    }

    fun addRoleTableAction() {
        rules.add(Rule("true", "true", "true"))
    }

    fun removeRuleTableAction() {
        rules.remove(ruleTableView.selectionModel.selectedItem)
    }
    fun removeFile() {
        files.remove(fileInfoTableView.selectionModel.selectedItem)
    }
    fun upRuleTableAction() {}
    fun downRuleTableAction() {}
    fun generateRenameDestFilesOfFormat() {
        if (!files.isEmpty()) {
            var startNumber = startNumberOfRenameTab!!.value
            val filePrefixString = filePrefix.value.trim()
            val filePostfixString = filePostfix.value.trim()
            files.forEach{
                val fileName = it.fileName
                it.newFileName= filePrefixString + fileName + (startNumber++) + filePostfixString
            }
            fileInfoTableView.refresh()
        }
    }

    fun generateRenameDestFilesOfReplace() {
        files.forEach{
            val fileName = it.fileName
            it.newFileName = fileName.replace(fileQueryString.value.trim().toRegex(), fileReplaceString.value.trim())
        }
        fileInfoTableView.refresh()
    }

    fun generateRenameDestFilesOfAddable() {
        files.forEach{
            val fileName = it.fileName
            it.newFileName = filePrefixAddableText.value.trim() + fileName + filePostfixAddableText.value.trim()
        }
//        for (fileInfo in files) {
//            val fileName = fileInfo.fileName
//            fileInfo.newFileName = filePrefixAddableText.value.trim() + fileName + filePostfixAddableText.value.trim()
//        }
        fileInfoTableView.refresh()
    }

    init {
//        files.addAll(
//                FileRename("FileRename", "", "", "", "")
//        )
//        rules.addAll(
//                Rule("Rule", "", "")
//        )
    }
}

fun main(){
//   val str=XmlUtil.parseXml(xmlStr)
//    val root=XmlUtil.getRootElement(str)
//    val out="""
//        class DemoV:View(""){
//            override val root = ${root.tagName.toLowerCase()}{
//
//            }
//        }
//
//    """.trimIndent()
    val json=JSONUtil.parseFromXml(xmlStr)
//    println(json.toStringPretty())
    println(json.keys)
}

val xmlStr="""
    <AnchorPane prefHeight="428.0" prefWidth="783.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.xwintop.xJavaFxTool.controller.littleTools.QRCodeBuilderController">
	<children>
      <BorderPane layoutX="24.0" layoutY="17.0" AnchorPane.bottomAnchor="10.0" AnchorPane.leftAnchor="10.0" AnchorPane.rightAnchor="10.0" AnchorPane.topAnchor="10.0">
         <top>
            <VBox alignment="CENTER" spacing="5.0" BorderPane.alignment="CENTER">
               <children>
                  <HBox alignment="CENTER" spacing="5.0">
                     <children>
                  		<Label text="地址：" />
                  		<TextField fx:id="contentTextField" prefWidth="308.0" />
                        <ChoiceBox fx:id="codeFormatChoiceBox" prefHeight="23.0" prefWidth="60.0" />
                  		<Button fx:id="builderButton" mnemonicParsing="false" onAction="#builderAction" text="生成" />
                        <Button fx:id="logoButton" mnemonicParsing="false" onAction="#logoAction" text="加载logo" />
                        <Button fx:id="snapshotButton" mnemonicParsing="false" onAction="#snapshotAction" text="截图识别">
                           <tooltip>
                              <Tooltip text="试试alt+s快捷键截图" />
                           </tooltip>
                        </Button>
                        <Button fx:id="snapshotDesktopButton" mnemonicParsing="false" onAction="#snapshotDesktopAction" text="识别桌面">
                           <tooltip>
                              <Tooltip text="试试alt+s快捷键截图" />
                           </tooltip>
                        </Button>
                        <Button fx:id="saveButton" mnemonicParsing="false" onAction="#saveAction" text="保存" />
                     </children>
                  </HBox>
                  <HBox alignment="CENTER" spacing="5.0">
                     <children>
                        <Label text="前景色：" />
                        <ColorPicker fx:id="onColorColorPicker" prefWidth="77.0" />
                        <Label text="背景色：" />
                        <ColorPicker fx:id="offColorColorPicker" prefWidth="78.0" />
                        <Label text="容错等级：" />
                        <ChoiceBox fx:id="errorCorrectionLevelChoiceBox" prefWidth="60.0" />
                        <Label text="边距：" />
                        <ChoiceBox fx:id="marginChoiceBox" prefWidth="42.0" />
                        <Label text="图片格式：" />
                        <ChoiceBox fx:id="formatImageChoiceBox" prefWidth="48.0" />
                        <CheckBox fx:id="logoCheckBox" mnemonicParsing="false" text="Logo" />
                     </children>
                  </HBox>
               </children>
            </VBox>
         </top>
         <center>
            <HBox alignment="CENTER" spacing="20.0" BorderPane.alignment="CENTER">
               <children>
            		<ImageView fx:id="codeImageView" fitHeight="320.0" fitWidth="320.0" pickOnBounds="true" preserveRatio="true" />
                  <ImageView fx:id="codeImageView1" fitHeight="320.0" fitWidth="320.0" pickOnBounds="true" preserveRatio="true" />
                  <VBox spacing="10.0">
                     <children>
                        <Label text="Logo大小">
                           <tooltip>
                              <Tooltip text="设置Logo大小" />
                           </tooltip>
                        </Label>
                        <Slider fx:id="logoSlider" orientation="VERTICAL" showTickLabels="true" showTickMarks="true" value="15.0" />
                     </children>
                     <HBox.margin>
                        <Insets top="10.0" />
                     </HBox.margin>
                  </VBox>
               </children>
               <BorderPane.margin>
                  <Insets top="10.0" />
               </BorderPane.margin>
            </HBox>
         </center>
      </BorderPane>
	</children>
</AnchorPane>
""".trimIndent()